# 内核配置
KERNEL_VERSION ?= 4.1.15
KERNELDIR ?= /home/xqyr/linux/xiong_lib/linux-imx-rel_imx_4.1.15_2.1.0_ga

# 项目配置
MODULE_NAME := charbeep
SRCS := main_file.c chardevice.c linux_gpio.c main.c
PWD := $(shell pwd)
BUILD_DIR := $(PWD)/build

# 安装配置
INSTALL_MOD_PATH ?= /home/xqyr/linux/file/nfs/root
MODULE_INSTALL_DIR := $(INSTALL_MOD_PATH)/lib/modules/$(KERNEL_VERSION)

# 构建目标
obj-m := $(MODULE_NAME).o
$(MODULE_NAME)-objs := $(SRCS:.c=.o)

# 构建标志
EXTRA_CFLAGS += -Wall -Werror

.PHONY: all build install clean help prepare_build_dir

all: build

prepare_build_dir:
	@mkdir -p $(BUILD_DIR)

build: prepare_build_dir
	@echo "Building kernel module $(MODULE_NAME)..."
	@$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
	@mkdir -p $(BUILD_DIR)
	@rm -f  $(SRCS:.c=.o) .*.cmd *.mod.* *.order *.symvers $(BUILD_DIR)/ 2>/dev/null || true
	@mv $(MODULE_NAME).ko $(BUILD_DIR)/$(MODULE_NAME).ko
	@echo ============================= $(MODULE_NAME).ko =================
	@modinfo $(BUILD_DIR)/$(MODULE_NAME).ko
	@echo ============================= END =================
	@echo "Build completed. Output: $(BUILD_DIR)/$(MODULE_NAME).ko"
	

install: build
	@echo "Installing module to $(MODULE_INSTALL_DIR)..."
	@mkdir -p $(MODULE_INSTALL_DIR)
	@cp -v $(BUILD_DIR)/$(MODULE_NAME).ko $(MODULE_INSTALL_DIR)
	@echo "Installation completed."

clean:
	@echo "Cleaning build files..."
	@$(MAKE) -C $(KERNELDIR) M=$(PWD) clean
	@rm -rf $(BUILD_DIR)
	@echo "Clean completed."